import * as http from 'http'
import * as path from 'path'


var url = 'http://thirdwx.qlogo.cn/mmopen/BEMV4WOAicktAAllnv9FdJFSU7QYVibMU62ctg7Ie5HiaCuDVCyiapibwrs48N97yrzLel03FvOUqAHEZGfBY5tCdnuHKEg4YvZSC/132' //一张网络图片
var url = 'https://i0.hdslb.com/bfs/vc/75ec2d45ce8c942a1f7379d4641171da4d90ab0d.png@1c.webp' //一张网络图片

function imgUrlToBase64(url: string, callBack: Function) {

  // 解决无法读取https的问题
  url = url.startsWith('https') ? url.replace('https', 'http') : url

  http.get(url, res => {
    const chunks: any[] = []
    let size = 0

    res.on('data', (chunk: Buffer) => {
      chunks.push(chunk)
      size += chunk.length //累加缓冲数据的长度
    })

    res.on('end', () => {
      const data = Buffer.concat(chunks, size)
      const base64Img = `data:image/${path.extname(url).slice(1)};base64,${data.toString('base64')}`
      callBack(base64Img)
    })
  })
}


imgUrlToBase64(url, (res: string) => {
  console.log(res)
})